<template>
  <div class='xtx-cart-page xtx-wrapper'>
    <div class="container">
      <xtx-bread>购物车</xtx-bread>
      <!-- 列表 -->
      <div class="xtx-cart" v-if="items.length">
        <table>
          <thead>
            <tr>
              <th class="check-column" width="120px">
                <xtx-checkbox :value="isSelectedAll" @change="checkAllFn">全选</xtx-checkbox>
              </th>
              <th width="400px">商品信息</th>
              <th width="220px">单价</th>
              <th width="180px">数量</th>
              <th width="180px">小计</th>
              <th width="140px">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="goods in validCartItems" :key="goods.skuId">
              <td class="check-column">
                <xtx-checkbox :value="goods.selected" @change="$event=chcekOne($event,goods)"></xtx-checkbox>
              </td>
              <td>
                <div class="product">
                  <img @click="$router.push('/product/'+goods.id)" :src="goods.picture" alt="">
                  <div class="info">
                    <p class="name ellipsis">{{goods.name}}</p>
                    <cart-sku @on-submit="$event=changeSku($event,goods)" :goods="goods" ></cart-sku>
                    <p class="tip" v-if="goods.stock<5">库存紧张，不足5件！</p>
                  </div>
                </div>
              </td>
              <td>
                <p class="mb10 fz18">¥{{parseFloat(goods.nowPrice).toFixed(2)}}</p>
                <p v-if="goods.price-goods.nowPrice>0">
                  <span>比加入时降价 </span>
                  <span class="red">￥{{(goods.price-goods.nowPrice).toFixed(2)}}</span>
                </p>
              </td>
              <td>
                <goods-number :max="goods.stock" :value="goods.count" @change="$event=>changCount($event,goods)" style="margin:0 auto">
                </goods-number>
              </td>
              <td>
                <p class="fz18 red">¥{{(goods.nowPrice*100*goods.count/100).toFixed(2)}}</p>
              </td>
              <td>
                <p class="mb10"><a href="#" @click.prevent="addCollect(goods)">移入收藏夹</a></p>
                <p class="mb10"><a href="#" class="green"  @click.prevent="deleteCart(goods)">删除</a></p>
                <p><a href="#" @click.prevent="$router.push('/same/'+goods.id)">找相似</a></p>
              </td>
            </tr>
          </tbody>
          <tbody v-if="unValidCartItems.length">
            <tr>
              <td colspan="6">
                <p class="invalid">失效商品</p>
              </td>
            </tr>
            <tr v-for="goods in unValidCartItems" :key="goods.skuId">
              <td class="check-column"></td>
              <td>
                <div class="product">
                  <img @click="$router.push('/product/'+goods.id)" :src="goods.picture" alt="">
                  <div class="info">
                    <p class="name gray ellipsis">{{goods.name}}</p>
                    <p class="gray">{{goods.attrsText}}</p>
                    <p class="gray">已售罄</p>
                  </div>
                </div>
              </td>
              <td><p class="fz18 gray">¥{{goods.price}}</p></td>
              <td><p class="gray">{{goods.count}}</p></td>
              <td><p class="fz18 gray">¥{{(goods.price*100*goods.count/100).toFixed(2)}}</p></td>
              <td>
                <p class="mb10"><a href="#" @click.prevent="$router.push('/same/'+goods.id)">找相似</a></p>
                <p><a href="#" class="green" @click.prevent="deleteCart(goods)">删除</a></p>
              </td>
            </tr>
          </tbody>
        </table>
        <div class="space"></div>
        <table class="footer">
          <thead>
            <tr>
              <th class="check-column" width="400px">
                <xtx-checkbox :value="isSelectedAll" @change="checkAllFn">全选</xtx-checkbox>
                <a href="#" @click.prevent="batchDeleteCart()">删除商品</a>
                <a href="#" @click.prevent="batchCollect()">移入收藏夹</a>
                <a href="#" @click.prevent="batchClear()">清空失效商品</a>
              </th>
              <th class="check-order" width="840px">
                <span>共 {{totalCount}} 件商品，已选择 {{selectedTotalCount}} 件</span> |
                <span>商品合计： ¥{{selectedTotalAmount}}</span> |
                <span>应付总额：<i>¥{{selectedTotalAmount}}</i></span>
                <a @click="checkout()" href="javascript:;" class="check-btn xtx-common-btn" type="primary">下单结算</a>
              </th>
            </tr>
          </thead>
        </table>
      </div>
      <div v-else class="xtx-cart">
        <div class="none">
          <img src="../../assets/images/none.png" alt="">
          <p>购物车内暂时没有商品</p>
          <div class="btn">
            <a href="#/" class="xtx-common-btn" type="primary">继续逛逛</a>
          </div>
        </div>
      </div>
      <!-- 猜你喜欢 -->
      <goods-relevant title="猜你喜欢"></goods-relevant>
    </div>
  </div>
</template>

<script>
import GoodsNumber from './components/goods-number'
import GoodsRelevant from './components/goods-relevant'
import CartSku from './components/cart-sku'
import { mapState, mapGetters, mapActions } from 'vuex'
export default {
  name: 'xtx-cart-page',
  components: { GoodsNumber, GoodsRelevant, CartSku },
  data () {
    return {
      checkAll: false,
      visibleDialog: false,
      // 选择sku当前商品
      currGoods: {}
    }
  },
  computed: {
    ...mapState('cart', ['items']),
    ...mapGetters('cart', [
      'totalCount',
      'unValidCartItems',
      'validCartItems',
      'selectedCartItems',
      'selectedTotalCount',
      'selectedTotalAmount'
    ]),
    isSelectedAll () {
      return this.selectedCartItems.length === this.validCartItems.length
    }
  },
  created () {
    this.getCart()
  },
  methods: {
    ...mapActions('cart', ['getCart', 'addCart', 'delCart', 'updateCart']),
    checkAllFn (checked) {
      this.validCartItems.forEach(async goods => {
        await this.updateCart({ skuId: goods.skuId, selected: checked })
      })
    },
    async chcekOne (checked, goods) {
      await this.updateCart({ skuId: goods.skuId, selected: checked })
    },
    async changCount (count, goods) {
      await this.updateCart({ skuId: goods.skuId, count })
    },
    async changeSku (skuInfo, goods) {
      console.log(skuInfo.skuId !== goods.skuId)
      if (skuInfo.skuId !== goods.skuId) {
        const sameGoods = this.validCartItems.find(item => item.skuId === skuInfo.skuId)
        if (sameGoods) {
          await this.delCart({ skuId: goods.skuId })
          await this.updateCart({ skuId: sameGoods.skuId, count: goods.count + sameGoods.count })
        } else {
          await this.delCart({ skuId: goods.skuId })
          await this.addCart({ ...goods, ...skuInfo })
        }
      }
    },
    deleteCart (goods) {
      this.$confirm({ text: '您确认从购物车删除该商品吗？' }).then(async (valid) => {
        if (valid) {
          await this.delCart(goods)
          this.$message({ message: '删除购物车商品成功', type: 'success' })
        }
      }).catch(e => {
        this.$message({ message: '删除购物车商品失败', type: 'error' })
      })
    },
    batchDeleteCart () {
      this.$confirm({ text: '您确认从购物车删除这些商品吗？' }).then(async (valid) => {
        if (valid) {
          await this.delCart(this.selectedCartItems)
          this.$message({ message: '批量删除购物车商品成功', type: 'success' })
        }
      }).catch(e => {
        this.$message({ message: '批量删除购物车商品失败', type: 'error' })
      })
    },
    batchClear () {
      this.$confirm({ text: '您确认清空无效商品吗？' }).then(async (valid) => {
        if (valid) {
          await this.delCart(this.unValidCartItems)
          this.$message({ message: '清空无效商品成功', type: 'success' })
        }
      }).catch(e => {
        this.$message({ message: '清空无效商品失败', type: 'error' })
      })
    },
    addCollect (goods) {
      this.checkLogin(() => {

      })
    },
    batchCollect () {
      this.checkLogin(() => {

      })
    },
    checkout () {
      this.checkLogin(() => {
        if (this.checkedTotal < 1) return this.$message({ type: 'warn', message: '请勾选商品' })
        this.$router.push('/member/checkout')
      })
    }
  }
}
</script>

<style scoped lang='less'>
@import './styles/cart.less';
.dialog-tip {
  text-align:center;
  font-size:16px;
  padding:10px 0 20px;
  color: @priceColor;
  i {
    font-size: 18px;
    margin-right: 5px;
  }
}
</style>
